package com.newcoder.community.controller;

import com.newcoder.community.annotation.LoginRequired;
import com.newcoder.community.entity.User;
import com.newcoder.community.service.FollowService;
import com.newcoder.community.service.LikeService;
import com.newcoder.community.service.UserService;
import com.newcoder.community.util.CommunityConstant;
import com.newcoder.community.util.CommunityUtil;
import com.newcoder.community.util.HostHolder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Field;

@Controller
@RequestMapping("/user")
public class UserController implements CommunityConstant {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;
    @Value("${community.path.domain}")
    private String domain;
    @Value("${community.path.upload}")
    private String uploadPath;
    @Value("${server.servlet.context-path}")
    private String contextPath;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private LikeService likeService;
    @Autowired
    private FollowService followService;
    @LoginRequired
    @RequestMapping(path = "/setting",method = RequestMethod.GET)
    public String getSettingPage(){
        return "/site/setting";
    }
    @LoginRequired
    @RequestMapping(path = "/upload",method = RequestMethod.POST)
    public String uploadHeader(MultipartFile headerImage, Model model){
        if(headerImage==null){
            model.addAttribute("error","您还没有选择图片!");
            return "/site/setting";
        }
        String filename = headerImage.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf("."));
        if(StringUtils.isBlank(suffix)){
            model.addAttribute("error","文件格式不正确!");
            return "/site/setting";
        }
        filename = CommunityUtil.generateUUID() + suffix;
        //确定文件存放的位置
        File dest = new File(uploadPath+"/"+filename);
        try {
            //存储文件
            headerImage.transferTo(dest);
        } catch (IOException e) {
            logger.error("上传文件失败："+e.getMessage());
            throw new RuntimeException("上传文件失败,服务器发生异常!"+e.getMessage());
        }
        //更新当前用户的头像(web访问路径)
        //http://localhost:8080/community/user/header/xxx.png
        User user = hostHolder.getUser();
        String headerUrl = domain+contextPath+"/user/header/"+filename;
        userService.updateHeader(user.getId(),headerUrl);
        return "redirect:/index";
    }
    @RequestMapping(path = "/header/{filename}",method = RequestMethod.GET)
    public void getHeader(@PathVariable("filename") String filename, HttpServletResponse response){
        //服务器存放的路径
       filename= uploadPath+"/"+filename;
       //文件后缀
        String suffix = filename.substring(filename.lastIndexOf("."));
       // 响应图片
        response.setContentType("image/"+suffix);
        try (FileInputStream fileInputStream = new FileInputStream(filename)){
            ServletOutputStream os = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int index =0;
            while((index=fileInputStream.read(buffer))!=-1){
                os.write(buffer,0,index);
            }
        } catch (IOException e) {
            logger.error("读取头像失败："+e.getMessage());
        }
    }
    @RequestMapping(path = "/passwordChange",method = RequestMethod.POST)
    public String setNewPassword(Model model,String password,String newPassword,String repeatPassword){
           if(StringUtils.isBlank(password)){
               model.addAttribute("passwordMsg","原密码不能为空!");
               return "/site/setting";
           }
        User user = hostHolder.getUser();
        String password1 = user.getPassword();
        String salt = user.getSalt();
        password = CommunityUtil.md5(password+salt);
        if(!password.equals(password1)){
            model.addAttribute("passwordMsg","原密码不正确!");
            return "/site/setting";
        }
        if(!newPassword.equals(repeatPassword)){
            model.addAttribute("newPasswordMsg","两次输入的密码不一致!");
            return "/site/setting";
        }
        userService.updatePassword(user.getId(),newPassword,salt);
        return "redirect:/index";
    }
    //个人主页
    @RequestMapping(path = "/profile/{userId}",method = RequestMethod.GET)
    public String getProfile(@PathVariable("userId") int userId,Model model){
        User user = userService.findUserById(userId);
        if(user==null){
            throw new RuntimeException("该用户不存在");
        }
        //用户的基本信息
        model.addAttribute("user",user);
        //用户获赞数量
        int userLikeCount = likeService.findUserLikeCount(userId);
        model.addAttribute("count",userLikeCount);
        //关注数量
        long followeeCount = followService.findFolloweeCount(userId, ENTITY_TYPE_USER);
        model.addAttribute("followeeCount",followeeCount);
        //粉丝的数量
        long followerCount = followService.findFollowerCount(ENTITY_TYPE_USER, userId);
        model.addAttribute("followerCount",followerCount);
        //是否已关注
        if(hostHolder.getUser()!=null){
            boolean hasFollowed = followService.hasFollowed(hostHolder.getUser().getId(), userId, ENTITY_TYPE_USER);
            model.addAttribute("hasFollowed",hasFollowed);
        }
        return "/site/profile";
    }

}
